
#include "../include/raylib.h"
#include <emscripten.h>
#include <emscripten/em_asm.h>
#include <emscripten/em_macros.h>
#include <emscripten/em_types.h>
#include <emscripten/emscripten.h>
#include <complex.h>
#include <stdio.h>
#include <string.h>
complex double c = 0;
bool ok = true;
complex double fc[30] = {0};
int mx[4000][4000] = {0};
char macstr[64]={0};

//复平面坐标转换屏幕坐标
Vector2 real_to_mpos(complex double val){
    double x = creal(val);
    double y = cimag(val);
    int px = (x-(-2.0))/0.001;
    int py = (y-(-2.0))/0.001;
    return (Vector2){px,4000-py};
}

void EMSCRIPTEN_KEEPALIVE chs(char *_macstr){
    strcpy(macstr,_macstr);
    printf("okok\n");
}

void DrawUpdate(void);

int main(){
    emscripten_set_window_title("hello");
    // emscripten_get_screen_size(, );
    InitWindow(4000, 4000,"hello");
    // SetTargetFPS(30);
    // EM_ASM_({
    //     var ptr = "你好";
    //     var buff = _malloc(64);
    //     stringToUTF8(ptr,buff,lengthBytesUTF8(ptr)+1);
    //     Module._chs(buff);
    //     _free(buff);
    // },0);
    char * _macstr = emscripten_run_script_string("\"hello\"");
    strcpy(macstr,_macstr);
    //计算某点是否满足该集合
    for (double i = -2.0;i < 2.0;i+=0.001){
        for (double ii=-2.0;ii < 2.0;ii+=0.001){
            fc[0] = 0;
            ok = true;
            c = i + ii*I;
            for ( int j = 0;j<29 ;j++){
                fc[j+1] = fc[j]*fc[j] + c;
                if (cabs(fc[j+1])>2.0){
                    ok = false;
                    break;
                }
            }
            if (ok==true){
                Vector2 npos = real_to_mpos(c);
                mx[(int)npos.x][(int)npos.y] = 1;
            }
        }
    }

    emscripten_set_main_loop(DrawUpdate, 30, 1);
    CloseWindow();
    return 0;
}

void DrawUpdate(void){
    BeginDrawing();
    ClearBackground(WHITE);
    DrawText(macstr, 100, 100, 24,RED );
    for (int i =100;i<3000 ;i++ ) {
        for (int j=940;j<3060 ; j++){
            if (mx[i][j]!=0){
                DrawPixel(i-100,j-940 , BLACK);
            }
        }
    }
    EndDrawing();
}
